﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.IO;
using System.Xml;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace Devtm.ServiceModel.UnitTest
{
    
    public static class MetadataHelper
    {


        public static IEnumerable<ServiceEndpoint> GetServiceEndpoints(this Type contract, Binding binding, EndpointAddress address)
        {

            List<ServiceEndpoint> endpoints = new List<ServiceEndpoint>();

            IEnumerable<ContractDescription> contractDescriptions =
                new System.Collections.ObjectModel.Collection<ContractDescription> { ContractDescription.GetContract(contract) };

            foreach (ContractDescription description in contractDescriptions)
                endpoints.Add(new ServiceEndpoint(description, binding, address));

            return endpoints;

        }


        public static string GetMetadata(Binding binding, EndpointAddress address, params Type[] contracts)
        {

            List<ServiceEndpoint> endpoints = new List<ServiceEndpoint>();

            foreach (Type Contract in contracts)
            {

                IEnumerable<ContractDescription> contractDescriptions =
                    new System.Collections.ObjectModel.Collection<ContractDescription> { ContractDescription.GetContract(Contract) };

                foreach (ContractDescription description in contractDescriptions)
                    endpoints.Add(new ServiceEndpoint(description, binding, address));

            }

            return GetMetadata(endpoints);

        }



        public static string GetMetadata(this IEnumerable<ServiceEndpoint> endpoints)
        {

            WsdlExporter exporter = new WsdlExporter() { PolicyVersion = PolicyVersion.Policy15 };

            foreach (ServiceEndpoint endpoint in endpoints)
                exporter.ExportEndpoint(endpoint);

            MetadataSet metadataDocs = null;

            if (exporter.Errors.Count == 0)
            {

                metadataDocs = exporter.GetGeneratedMetadata();

                // Serialize
                using (StringWriter sWriter = new StringWriter())
                {
                    XmlWriter writer = XmlWriter.Create(sWriter);
                    metadataDocs.WriteTo(writer);
                    writer.Flush();
                    return sWriter.ToString();
                }

            }

            return string.Empty;

        }



    }

}
